#include "crow.h"
#include <fstream>
#include <string>
#include <unordered_map>

// MIME类型映射
std::unordered_map<std::string, std::string> mimeTypes = {
    {".html", "text/html"},
    {".htm", "text/html"},
    {".css", "text/css"},
    {".js", "application/javascript"},
    {".json", "application/json"},
    {".png", "image/png"},
    {".jpg", "image/jpeg"},
    {".jpeg", "image/jpeg"},
    {".gif", "image/gif"},
    {".svg", "image/svg+xml"},
    {".ico", "image/x-icon"}
};

// 获取文件扩展名
std::string getFileExtension(const std::string& filename) {
    size_t dotPos = filename.find_last_of('.');
    if (dotPos != std::string::npos) {
        return filename.substr(dotPos);
    }
    return "";
}

// 获取MIME类型
std::string getMimeType(const std::string& filename) {
    std::string ext = getFileExtension(filename);
    if (mimeTypes.find(ext) != mimeTypes.end()) {
        return mimeTypes[ext];
    }
    return "application/octet-stream"; // 默认二进制类型
}

// 读取文件内容
std::string readFile(const std::string& filepath) {
    std::ifstream file(filepath, std::ios::binary);
    if (!file) {
        return "";
    }
    
    // 获取文件大小
    file.seekg(0, std::ios::end);
    size_t size = file.tellg();
    file.seekg(0, std::ios::beg);
    
    // 读取文件内容
    std::string content(size, '\0');
    file.read(&content[0], size);
    
    return content;
}

// 设置静态文件处理路由
void setupStaticFileHandler(crow::App<crow::CORSHandler>& app, const std::string& publicDir = "public") {
    CROW_ROUTE(app, "/static/<path>")
    ([publicDir](const crow::request& req, std::string path) {
        std::string filepath = publicDir + "/" + path;
        std::string fileContent = readFile(filepath);
        
        if (fileContent.empty()) {
            return crow::response(404, "文件未找到");
        }
        
        // 设置MIME类型
        crow::response res(200, fileContent);
        res.set_header("Content-Type", getMimeType(filepath));
        return res;
    });
    
    // 处理根路径
    CROW_ROUTE(app, "/")
    ([publicDir]() {
        std::string filepath = publicDir + "/index.html";
        std::string fileContent = readFile(filepath);
        
        if (fileContent.empty()) {
            filepath = publicDir + "/map.html"; // 尝试加载map.html作为默认页面
            fileContent = readFile(filepath);
            
            if (fileContent.empty()) {
                return crow::response(404, "首页未找到");
            }
        }
        
        // 设置MIME类型
        crow::response res(200, fileContent);
        res.set_header("Content-Type", "text/html");
        return res;
    });
} 